<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\ActivityOrder;
use think\Db;
use app\common\model\Stadium as StadiumModel;
use app\common\model\StadiumOrder;
use app\common\model\User;
use think\Exception;

/**
 * 首页接口
 */
class Stadium extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];
    public function getDate()
    {
        // 获取当前日期
        $currentDate = new \DateTime();
        // 初始化结果数组
        $weekArray = [];

// 循环生成接下来一周的日期
        for ($i = 0; $i < 7; $i++) {
            // 克隆当前日期对象以避免修改原始对象
            $date = clone $currentDate;
            $date->modify("+{$i} day");

            // 获取周几的中文全称
            $weekDays = ["日", "一", "二", "三", "四", "五", "六"];
            $weekText = "周" . $weekDays[$date->format('w')]; // w 返回的是 0（表示星期日）到 6（表示星期六）的数字

            // 获取日期字符串
            $dateString = $date->format('Y-m-d');

            // 获取格式化的月日
            $dateText = $date->format('m.d');
            $time_interval = [
                'top'=>[
                    [
                        'text'=>'08:00-08:30',
                        'date'=>$dateString . ' 08:00-08:30',
                    ],
                    [
                        'text'=>'08:30-09:00',
                        'date'=>$dateString . ' 08:30-09:00',
                    ],
                    [
                        'text'=>'09:00-09:30',
                        'date'=>$dateString . ' 09:00-09:30',
                    ],
                    [
                        'text'=>'11:00-11:30',
                        'date'=>$dateString . ' 11:00-11:30',
                    ],
                ],
                'afternoon'=>[
                    [
                        'text'=>'13:00-13:30',
                        'date'=>$dateString . ' 13:00-13:30',
                    ],
                    [
                        'text'=>'13:30-14:00',
                        'date'=>$dateString . ' 13:30-14:00',
                    ],
                    [
                        'text'=>'15:00-15:30',
                        'date'=>$dateString . ' 15:00-15:30',
                    ],
                    [
                        'text'=>'17:00-17:30',
                        'date'=>$dateString . ' 17:00-17:30',
                    ],
                ]
            ];
            // 将结果添加到数组中
            $weekArray[] = [
                'week_text' => $weekText,
                'date' => $dateString,
                'date_text' => $dateText,
                'time_interval'=>$time_interval
            ];
        }

        $this->success('ok',$weekArray);
    }
    /**
     * 场馆列表
     * @return void
     */
    public function getList()
    {
        $list = StadiumModel::where('status',1)->order('id asc')->paginate()->each(function ($item){
            $item['labels'] = explode(',',$item['labels']);
            return $item;
        });
        $this->success('ok',$list);
    }

    /**
     * 活动详情
     * @return void
     */
    public function getDetail()
    {
        $id = $this->request->post('id');
        $detail = StadiumModel::get($id);
        $detail['labels'] = explode(',',$detail['labels']);
        $this->success('ok',$detail);
    }

    /**
     * 预约提交
     * @return void
     */
    public function addOrder()
    {
        $stadium_id = $this->request->post('stadium_id');
        $yd_type = $this->request->post('yd_type');
        $yy_times = $this->request->post('yy_times/a');
        $pay_type = $this->request->post('pay_type');
        $stadium = StadiumModel::get($stadium_id);
        if(!$stadium){
            $this->error('场馆不存在');
        }
        if($stadium['status'] != 1){
            $this->error('场馆状态错误');
        }

//        $yy_times_arr = explode('|',$yy_times);
        $yy_times_arr = $yy_times;
        if(!$yy_times_arr || !$yd_type){
            $this->error('请选择预约时间');
        }

        //查询此用户预约的所有课程
//        $course_list = Db::name('timetable')->alias('t')
//            ->join('course_order pre','pre.course_id=t.course_id','left')
//            ->where('pre.user_id',$this->auth->id)->field('t.c_time,t.time')->select();
        $course_list = Db::name('timetable')->where('stadium_name',$stadium->name)->field('c_time,time')->select();
        foreach ($course_list as $item){

            $time = explode('-',$item['c_time']);
            $start = date('Y-m-d',$item['time']).' '.$time[0];
            $end = date('Y-m-d',$item['time']).' '.$time[1];
            foreach ($yy_times_arr as $k=>$v){
                if($yd_type == 1){//按天预约
                    if(strtotime(date('Y-m-d',$item['time'])) == strtotime($v)){
                        $this->error('您预约的时间段有课程，请重新选择');
                    }
                }else{
                    $times = explode(' ',$v);
                    $time_h = explode('-',$times[1]);
                    $starts = $times[0] .' '. $time_h[0];
                    $ends = $times[0] .' '. $time_h[1];
                    if(strtotime($starts) <= strtotime($start) && strtotime($start) <= strtotime($ends)){
                        $this->error('您预约的时间段有课程，请重新选择');
                    }
                }

            }
        }

        if($yd_type == 1){//按天
            $price = $stadium->day_price * count($yy_times_arr);
        }else{
            $price = $stadium->hours_price * count($yy_times_arr);
        }
        $data = [
            'order_no'=>date('YmdHis').mt_rand(1000,9999),
            'yd_type'=>$yd_type,
            'yy_times'=>trim(implode('|',$yy_times_arr),'|'),
            'stadium_id' => $stadium_id,
            'user_id' => $this->auth->id,
            'total_price'=>$price,
            'pay_type'=>$pay_type,
            'status'=>0,
            'createtime'=>time(),
            'updatetime'=>time(),
        ];
        if($price == 0){
            $order = StadiumOrder::create($data);
            //直接回调
            StadiumOrder::paysuccess($order->order_no,$price,'score');
            $this->success('ok',$order);
        }else{
            //积分支付
            if($pay_type == 'score'){
                //查询积分是否充足
                if($this->auth->score < $price){
                    $this->error('积分不足');
                }
                try{
                    Db::startTrans();
                    $order = StadiumOrder::create($data);
                    //扣除积分
                    User::score(-$price, $this->auth->id, '预约场馆');
                    //直接回调
                    StadiumOrder::paysuccess($order->order_no,$price,'score');
                    Db::commit();
                }catch (\Exception $e){
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success('ok',$order);
            }else{
                $order = StadiumOrder::create($data);
                $request = \think\Request::instance();
                $notifyurl = $request->root(true) . '/api/stadium/epay/type/notify/paytype/' . 'wechat';
                $params = [
                    'amount'=>$price,
                    'orderid'=>$order->order_no,
                    'type'=>"wechat",
                    'title'=>"预约场馆",
                    'notifyurl'=>$notifyurl,
//                'returnurl'=>"返回地址",
                    'method'=>"miniapp",
                    'openid'=>$this->auth->openid,
                ];
                $res = \addons\epay\library\Service::submitOrder($params);
                $this->success('ok',$res);
            }
        }


    }

    /**
     * 企业支付通知和回调
     */
    public function epay()
    {
        $type = $this->request->param('type');
        $paytype = $this->request->param('paytype');
        if ($type == 'notify') {
            $pay = \addons\epay\library\Service::checkNotify($paytype);
            if (!$pay) {
                echo '签名错误';
                return;
            }
            $data = $pay->verify();
            try {
                $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
//                \addons\recharge\library\Order::settle($data['out_trade_no'], $payamount);
                //直接回调
                StadiumOrder::paysuccess($data['out_trade_no'],$payamount,'wechat');
            } catch (Exception $e) {
            }
            return $pay->success()->send();
        } else {
//            $pay = \addons\epay\library\Service::checkReturn($paytype);
//            if (!$pay) {
//                $this->error('签名错误');
//            }
//            //微信支付没有返回链接
//            if ($pay === true) {
//                $this->success("请返回网站查看支付状态!", "");
//            }

            //你可以在这里定义你的提示信息,但切记不可在此编写逻辑
            $this->success("恭喜你！充值成功!", url("user/index"));
        }
        return;
    }

    /**
     * 订单列表
     * @return void
     * @throws \think\exception\DbException
     */
    public function getOrderList()
    {
        $status = $this->request->post('status');
        $map = [];
        if($status){
            $map['status'] = $status;
        }
        $list = StadiumOrder::where('user_id',$this->auth->id)
            ->where('status','neq',0)
            ->where($map)
            ->order('createtime desc')->paginate()->each(function ($item){
                $item['yy_times_arr'] = explode('|',$item['yy_times']);
                $item['stadium'] = StadiumModel::where('id',$item['stadium_id'])->find();
                return $item;
            });
        $this->success('ok',$list);
    }

    /**
     * 订单详情
     * @return void
     */
    public function getOrderDetail()
    {
        $order_id = $this->request->post('order_id');
        $order = StadiumOrder::get($order_id);
        $order['yy_times_arr'] = explode('|',$order['yy_times']);
        if(!$order){
            $this->error('订单不存在');
        }
        if($order['user_id'] != $this->auth->id){
            $this->error('您无权查看此订单');
        }
        $order['stadium'] = StadiumModel::where('id',$order['stadium_id'])->find();
        $this->success('ok',$order);
    }

    /**
     * 取消订单
     * @return void
     */
    public function cancelOrder()
    {
        $order_id = $this->request->post('order_id');
        $order = StadiumOrder::get($order_id);
        if(!$order){
            $this->error('订单不存在');
        }
        if($order['user_id'] != $this->auth->id){
            $this->error('您无权取消此订单');
        }
        if($order['status'] != 1){
            $this->error('订单状态错误');
        }
        $times = explode('|',$order['yy_times']);

        foreach ($times as $time){
            if($order->yd_type == 1){//按天
                if(strtotime($time) - time() < config('site.stadium_cancel') * 60 * 60){
                    $this->error('订单已超过可取消时间');
                }
            }else{//小时
                $timess = explode(' ',$time);
                $time_h = explode('-',$timess[1]);
                $starts = $timess[0] .' '. $time_h[0];
                $ends = $timess[0] .' '. $time_h[1];
                if((strtotime($starts) - time()) < config('site.stadium_cancel') * 60 * 60 || (strtotime($ends) - time()) < config('site.stadium_cancel') * 60 * 60){
                    $this->error('订单已超过可取消时间');
                }
            }

        }
        $order->status = 3;
        $order->cancel_time = time();
        if($order->pay_type == 'wechat'){
            $this->error('暂未开放');
        }
        if($order->save()){
            if($order->pay_type == 'score'){
                User::score($order->score_fee, $this->auth->id, '订单取消返还金额');
            }
            $this->success('取消成功',$order);
        }else{
            $this->error('取消失败');
        }
    }

}
